require(['jquery','knockout','bootstrap', 'uui', 'tree', 'grid', 'ip'], function ($, ko) {
	window.ko = ko;
	var currentPage = 1;
	var totalCount;
	var limit;
	var flag = 0;
	var cidFlag;
	var cid;
	var bid;
	var viewModel = {
		//ruleName: ko.observable(viewModel.gridDataTable.meta.rule_name),
		//定值规则树数据模型
		listDataTable: new u.DataTable({
			meta : {
				'cid' : {
					type : 'string'
				},
				'pid' : {
					type : 'string'
				},
				'cname' : {
					type : 'string'
				}
			}
		}),
		treeSetting: {
			view: {
				showLine: false,
				selectedMulti: true,
			},
			callback: {
				onClick: function (e, id, node) {
					cid = node.cid;
					cidFlag = node.cid;
					showgrid();
				}
			}
		},
		//表格数据模型
		gridDataTable: new u.DataTable({
			meta: {
				'bname': {type: 'string'},
				'press': {type: 'string'},
				'author': {type: 'string'},
			}
		})
	};
	
	var bname;
	var row;
	var rowindex;
	viewModel.getSelectedEleRuleDeatilId = function(obj){
    	row = viewModel.gridDataTable.getFocusRow();
    	bid=row.getSimpleData().bid;
    	bname= row.getSimpleData().bname;
    	rowindex=obj.rowIndex;
    };
    
    /*
     * 删除产品
     */
    viewModel.delProduct = function() {
    	layer.confirm('确认要删除' + bname + '吗？',function(index){
			$.ajax({
				type : "POST",
				url : "/bookstore/my/delProduct",
				data : {
					"bid" : bid,
				},
				dataType : 'json',
				success : function(result) {
					showgrid();
					layer.msg('删除成功!',{icon:1,time:1000});
				},
				error : function() {
					layer.msg('删除失败!',{icon:2,time:1000});
				}
			});
		});
    }
    
    //查看图片
    viewModel.getImage = function() {
    	if(!row) {
    		layer.alert("请选择要查看的书籍！\r\n",{
                title: '提示框',				
				icon:0,								
			   });
    		return false;
    	}
    	$("#img-content").show();
		$("#settoverlay").fadeTo(200,0.5);
		var filePath= row.getSimpleData().image_w;
		var img = document.getElementById("bus-img");
		img.src = "";
		img.src = "/bookstore/my/getImage" + "?" + "filePath=" + encodeURI(encodeURI(filePath));
    }
    
    //关闭查看
    closeImg = function() {
 		$("#settoverlay").fadeOut(200);
 		$("#img-content").hide();
 	}
	
	function showgrid() {
		$.ajax({
			type : "GET",
			url : "/bookstore/my/findAll",
			data : {
				"cid" : cid,
				"currentPage" : currentPage,
				"limit" : 12
			}, 
			dataType : 'json',
			success : function(result) {
				viewModel.gridDataTable.clear();
				var data = result.data;
				viewModel.gridDataTable.setSimpleData(data);
				//设置分页插件所需参数
				totalCount = result.totalCount;
		    	limit = 12;
		    	if (!flag || cidFlag!=null) { // 保证分页插件只生成一次
		    		flag = 1;
		    		currentPage = 1;
		    		callBackPagination(totalCount, limit);
		    	}
		    	cidFlag = null;
			},
			error : function() {
				alert("网络有问题吧。。。");
			}
		})
	};
	
	//请求数据，刷新左侧定值规则树
    function getTree(){
        $.ajax({
            type: 'GET',
            url: "/bookstore/my/findTree",
            dataType: 'json',
            success: function (result) {
            	viewModel.listDataTable.setData(result.data);
            	console.log(result);
            	//展开所有子节点
        		var treeObj = $.fn.zTree.getZTreeObj("tree2");
        		console.log(treeObj);
        		treeObj.expandAll(true);
            },
            error: function () {
            	alert("树不出来，网络有问题吧。。。");
            }
        });
    };
    
    /**
     * 分页插件
     * callback:点击事件
     */
    function callBackPagination(totalCount, limit) {
        $('#callBackPager').extendPagination({
            totalCount: totalCount, //总页数
            showCount: 10,          //展示选项数
            limit: limit,           //每页条数
            callback: function (cur, limit, totalCount) {
            	currentPage = cur;
            	showgrid();
            	//alert('当前页：' + cur + '每页条数：' + limit + '总数：' + totalCount);
            }
        });
    }
    
    //折扣计算
    getDistcount = function() {
  		var price = $("#pricing").val();
  		var currprice = $("#currPrice").val();
  		if(price && currprice) {
  			var discount = (currprice/price).toFixed(2);
  			discount = discount * 10;
  	  		$("#discount").val(discount　+ "折");
  		}
  	}
    
    //下拉框获取信息
    getEdtion = function() {
    	var editon = $("#edition"); 
    	var category = $("#category");
    	editon.html("");
    	category.html("");
		var choice_editon = '<option>' + 1 + '</option>';
		var choice_category = '<option>' + '请选择分类' + '</option>';
		editon.append(choice_editon);
		category.append(choice_category);
		for (var i = 2; i < 6; i++) {
			var temp = '<option>' + i + '</option>';
			editon.append(temp);
		}
		$.ajax({
			type : 'GET',
			url :  "/bookstore/my/getCategory",
			dataType : 'json',
			success : function(result) {
				var data = result.data; // 
				for (var i = 0; i < data.length; i++) {
					var tempCat = '<option>' + data[i].cid +' '+data[i].cname + '</option>';
					category.append(tempCat);
				}
			}
		});
    }
    
    //新增书籍
    viewModel.addProduct = function() {
    	//清空数据
    	$('#bname').val('');
    	$('#author').val('');
    	$('#pricing').val('');
    	$('#currPrice').val('');
    	$('#discount').val('');
    	$('#press').val('');
    	$('#publicationTime').val('');
    	$('#edition').val('1');
    	$('#category').val('请选择分类');
    	$('#image_w').val('');
    	layer.open({
	        type: 1,
	        title: '添加书籍',
			maxmin: true, 
			shadeClose:false, //点击遮罩关闭层
	        area : ['800px' , ''],
	        content:$('#add_menber_style'),
			btn:['提交','取消'],
			yes:function(index,layero) {
			var data = new FormData($('#productForm')[0]);
			console.log(data);
			 var num=0;
			 var str="";
			 $(".add_menber input[type$='text']").each(function(n){
		          if($(this).val()=="") {
					   layer.alert(str+=""+$(this).attr("name")+"不能为空！\r\n",{
		                title: '提示框',				
						icon:0,								
		          }); 
				    num++;
		            return false;            
		          } 
			 });
			if (num > 0) {
				return false;
			}
			$.ajax({
				type : "POST",
				url : "/bookstore/my/addBook",
					data : data,
					dataType : 'json',
					async: false,
					cache: false,
					processData:false,
					contentType: false,
					success : function(result) {
					showgrid();
					layer.alert('添加成功！',{
			               title: '提示框',				
						   icon:1,		
						  });
				    layer.close(index);
				},
				error : function() {
					layer.alert('添加失败！',{
			               title: '提示框',				
						   icon:2,		
						  });
					return false;
				}
			});
		  }
	    });
    }
    
    //编辑书籍
    viewModel.editProduct = function() {
    	if(!row) {
    		layer.alert("请选择要编辑的书籍！\r\n",{
                title: '提示框',				
				icon:0,								
			   }); 
    		return false;
    	} 
    	$('#bid').val(row.getSimpleData().bid);
    	$('#bname').val(row.getSimpleData().bname);
    	$('#author').val(row.getSimpleData().author);
    	$('#pricing').val(row.getSimpleData().pricing);
    	$('#currPrice').val(row.getSimpleData().currPrice);
    	$('#discount').val(row.getSimpleData().discount+'折');
    	$('#press').val(row.getSimpleData().press);
    	$('#publicationTime').val(row.getSimpleData().publicationTime);
    	$('#edition').val(row.getSimpleData().edition);
    	var catArray = [];
    	$("#category option").each(function(){ //遍历全部option
            var text = $(this).text(); //获取option的内容
            catArray.push(text); //添加到数组中
        });
    	for (var i = 0; i < catArray.length; i ++) {
    		if (catArray[i].indexOf(row.getSimpleData().cid) > -1) {
    			$('#category').val(catArray[i]);
    			break;
			}
    	}
    	layer.open({
	        type: 1,
	        title: '编辑'+row.getSimpleData().bname,
			maxmin: true, 
			shadeClose:false, //点击遮罩关闭层
	        area : ['800px' , ''],
	        content:$('#add_menber_style'),
			btn:['提交','取消'],
			yes:function(index,layero) {
			var data = new FormData($('#productForm')[0]);
			console.log(data);
			 var num=0;
			 var str="";
			 $(".add_menber input[type$='text']").each(function(n){
		          if($(this).val()=="") {
					   layer.alert(str+=""+$(this).attr("name")+"不能为空！\r\n",{
		                title: '提示框',				
						icon:0,								
					   }); 
				    num++;
		            return false;            
		          } 
			 });
			if (num > 0) {
				return false;
			}
			$.ajax({
				type : "POST",
				url : "/bookstore/my/editBook",
					data : data,
					dataType : 'json',
					async: false,
					cache: false,
					processData:false,
					contentType: false,
					success : function(result) {
					showgrid();
					layer.alert('编辑成功！',{
			               title: '提示框',				
						   icon:1,		
						  });
				    layer.close(index);
				},
				error : function() {
					layer.alert('编辑失败！',{
			               title: '提示框',				
						   icon:2,		
						  });
					return false;
				}
			});
		  }
	    });
    }
    
	function init(){
		getEdtion();
		showgrid();
		getTree();
		//ko.cleanNode($("#list-page")[0]);
		var app = u.createApp(
				{
					el: '#first',
					model: viewModel
				}
		);
    };
    

    init();

});